/**
 * Copyright © 2013 Creativor Studio.
 * About license information, please see LICENSE.txt.
 */
package org.creativor.rayson.serialize;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * @author creativor
 * 
 */
public class ObjectType extends SerializableType<Object> {

	/**
	 * @param type
	 */
	protected ObjectType(final byte type) {
		super(type);
	}

	@Override
	Object read(final DataInput dis) throws SerializeFormatException, IOException {
		// read class name.
		final int length = dis.readShort();
		final byte[] bytes = new byte[length];
		dis.readFully(bytes);
		final String clsName = new String(bytes);
		try {
			final Class<?> klass = Class.forName(clsName);
			return klass.newInstance();
		} catch (final ClassNotFoundException e) {
			throw new SerializeFormatException("Can not load class: " + clsName, e);
		} catch (final Exception e) {
			throw new SerializeFormatException("Can not new instance of: " + clsName, e);
		}
	}

	@Override
	Object readArray(final DataInput dis, final int arrayLength) {
		return null;
	}

	@Override
	protected void readFields(final DataInput dis, final Object obj) throws IOException,
			SerializeFormatException {
		
		super.readFields(dis, obj);
	}

	@Override
	void write(final DataOutput dos, final Object value) throws IOException,
			UnsupportedTypeException {
		// write object class name.
		final String clsName = value.getClass().getName();
		dos.writeShort(clsName.length());
		dos.write(clsName.getBytes());
	}

	@Override
	void writeArray(final DataOutput dos, final Object array) throws IOException,
			UnsupportedTypeException {
		// TODO Auto-generated method stub

	}

	@Override
	protected void writeFields(final DataOutput dos, final Object obj) throws IOException {
		// write EOF
		super.writeFields(dos, obj);
	}
}